package base62

import (
	"fmt"
	"math/big"
)

const base62Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

func Encode(num int64) string {
	if num == 0 {
		return string(base62Chars[0])
	}

	var result []byte
	base := big.NewInt(62)
	number := big.NewInt(num)

	for number.Cmp(big.NewInt(0)) > 0 {
		mod := new(big.Int).Mod(number, base)
		result = append(result, base62Chars[mod.Int64()])
		number.Div(number, base)
	}

	// Reverse the result to get the correct order
	for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
		result[i], result[j] = result[j], result[i]
	}

	return string(result)
}

func Decode(encoded string) (int64, error) {
	var result big.Int
	base := big.NewInt(62)

	for _, char := range encoded {
		index := -1
		for i, c := range base62Chars {
			if char == c {
				index = i
				break
			}
		}
		if index == -1 {
			return 0, fmt.Errorf("invalid character in input")
		}

		result.Mul(&result, base)
		result.Add(&result, big.NewInt(int64(index)))
	}

	return result.Int64(), nil
}
